package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@RestController
//当前Controller中所有的方法在绑定请求路径时,如果有重复的,可以放在@RequestMapping注解中
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession httpSession;

    @ApiOperation("注册模块")
    @PostMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println(userRegDTO);
        //获取注册用户名,验证是否为重复用户
        String username = userRegDTO.getUsername();
        User findUser = userMapper.selectByUsername(username);
        if(findUser != null){
            return 2;
        }


        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;

    }
    @ApiOperation("登录模块")
    @PostMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        System.out.println(userLoginDTO);
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user!= null) {
            if (user.getPassword().equals(userLoginDTO.getPassword())) {
                session.setAttribute("user",user);
                return 1;
            }else {
                return 2;
            }
        }else {
            return 3;
        }
    }
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        User user = (User)session.getAttribute("user");
        if (user == null) {
            return null;
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }

    }

    @ApiOperation("登出模块")
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
